const rootPath  = '../../../';
var request     = require(rootPath + 'common/request.js');
var common      = require(rootPath + 'common/common.js');
var util        = require(rootPath + 'util/util.js');
var Promise     = require(rootPath + 'util/promise.js');
var options     = {
    data : {
        title           : '',
        description     : '',
        chooseImages    : [],
        startMoney      : 0,
        originMoney     : 0,
        mobile          : '',
        ages            : ['0 - 1', '2 - 3', '4 - 5', '> 5'],
        ageIndex        : 0,
        addressName     : '请选择位置',
        addressDetail   : '',
        addressLat      : '',
        addressLng      : '',
        loading         : false,
        hasUpload       : false,
    },
    onLoad : function () {
        request.getUserInfo().then(request.saveWechatUserInfo).catch(e => {
            console.log(e);
        });
    },
    catchChooseImage : function (e) {
        let that        = this;
        let imageCount  = that.data.chooseImages.length;

        if (imageCount >= 9) {
            wx.showToast({
                title       : '最多9张图片哦!',
                icon        : 'success',
                duration    : 1000,
                mask        : true,
            });

            return false;
        }

        common.chooseImage(9 - imageCount).then(response => {
            let tempArray = response.tempFilePaths.map(tempFile => {
                return {
                    upload  : false,
                    wxfile  : tempFile,
                    path    : null,
                };
            });

            that.setData({
                chooseImages : that.data.chooseImages.concat(tempArray),
            });

            Object.keys(that.data.chooseImages).map(key => {
                that.uploadImages(key, that.data.chooseImages[key].wxfile);
            });
        }).catch(e => {
            console.log(e);
        });
    },
    catchDeleteImage : function (e) {
        let index = e.currentTarget.dataset.index;

        this.data.chooseImages.splice(index, 1);
        this.setData({
            chooseImages : this.data.chooseImages,
        });
    },
    bindAgeChange : function (e) {
        this.setData({
            ageIndex : e.detail.value,
        });
    },
    catchChooseLocation : function () {
        let that = this;

        wx.chooseLocation({
            success : response => {
                that.setData({
                    addressName     : response.name,
                    addressDetail   : response.address,
                    addressLat      : response.latitude,
                    addressLng      : response.longitude,
                });
            },
        });
    },
    uploadImages : function (index, wxfile) {
        let that    = this;
        let upload  = that.data.chooseImages[index].upload;
        let path    = that.data.chooseImages[index].path;

        if (upload && path) {
            return true;
        }

        request.uploadImage(wxfile).then(response => {
            let data = JSON.parse(response.data);

            if (data.code === 'success') {
                that.data.chooseImages[index].upload    = true;
                that.data.chooseImages[index].path      = data.data.webpath;
                that.setData({
                    chooseImages : that.data.chooseImages,
                });
            } else {
                wx.showToast({
                    title   : data.message,
                    icon    : 'loading',
                });
            }
        }).catch(e => {
            console.log(e);
            wx.showToast({
                title   : e.errMsg,
                icon    : 'loading',
            });
        });
    },
    bindPublishProduct : function (e) {
        let that = this;
        if (!that.checkCanPublish()) {
            return false;
        }

        let images  = [];
        for (let img of that.data.chooseImages) {
            images.push(img.path);
        }

        let all     = that.data;
        let data    = {
            name            : all.title,
            description     : all.description,
            images          : images,
            address_name    : all.addressName,
            position        : all.addressDetail,
            lat             : all.addressLat,
            lng             : all.addressLng,
            reserve_price   : all.startMoney,
            original_price  : all.originMoney,
            age_range       : all.ages[all.ageIndex],
            mobile          : all.mobile,
            form_id         : e.detail.formId,
        };

        if (that.loading) {
            return false;
        }

        that.setData({
            loading : true,
        });

        wx.showToast({
            title   : '发布中...',
            icon    : 'loading',
        });

        request.storeProduct(data).then(response => {
            let data = response.data;
            console.log(response);

            that.setData({
                loading : false,
            });

            if (data.code === 'success') {
                wx.showToast({
                    title   : '物品发布成功哦!',
                    icon    : 'success',
                    success : res => {
                        wx.navigateBack();
                    }
                });
            } else {
                wx.showToast({
                    title   : data.message,
                    icon    : 'loading',
                });
            }
        }).catch(e => {
            console.log(e);
        });
    },
    bindInputMobile : function (e) {
        this.setData({
            mobile : e.detail.value,
        });
    },
    bindInputTitle : function (e) {
        this.setData({
            title : e.detail.value,
        });
    },
    bindInputDesc : function (e) {
        this.setData({
            description : e.detail.value,
        });
    },
    bindInputStartMoney : function (e) {
        this.setData({
            startMoney : e.detail.value,
        });
    },
    bindInputOriginMoney : function (e) {
        this.setData({
            originMoney : e.detail.value,
        });
    },
    checkCanPublish : function () {
        let that = this;

        if (that.data.title === '') {
            wx.showToast({
                title   : '请输入产品标题!',
                icon    : 'loading',
            });

            return false;
        }

        if (that.data.description === '') {
            wx.showToast({
                title   : '请输入产品描述!',
                icon    : 'loading',
            });

            return false;
        }

        if (that.data.chooseImages.length === 0) {
            wx.showToast({
                title   : '请上传一些产品图片吧!',
                icon    : 'loading',
            });

            return false;
        }

        if (that.data.addressLat === '' || that.data.addressLng === '') {
            wx.showToast({
                title   : '选择一下产品地址吧!',
                icon    : 'loading',
            });

            return false;
        }

        if (!that.data.startMoney) {
            wx.showToast({
                title   : '请输入一下起拍价格吧!',
                icon    : 'loading',
            });

            return false;
        } else {
            let money = Number(that.data.startMoney);

            if (isNaN(money) || money <= 0) {
                wx.showToast({
                    title   : '起拍价格式不对哦!',
                    icon    : 'loading',
                });

                return false;
            }
        }

        if (!that.data.originMoney) {
            wx.showToast({
                title   : '请输入一下产品原价吧!',
                icon    : 'loading',
            });

            return false;
        } else {
            let money = Number(that.data.originMoney);

            if (isNaN(money) || money <= 0) {
                wx.showToast({
                    title   : '产品原价格式不对哦!',
                    icon    : 'loading',
                });

                return false;
            }
        }

        if (!util.isMobile(that.data.mobile)) {
            wx.showToast({
                title   : '您的联系方式格式错误哦!',
                icon    : 'loading',
            });

            return false;
        }

        for (let key of Object.keys(that.data.chooseImages)) {
            if (!that.data.chooseImages[key].upload) {
                that.uploadImages(key, that.data.chooseImages[key].wxfile);

                wx.showToast({
                    title   : '请稍等图片上传!',
                    icon    : 'loading',
                });

                return false;
            }
        }

        return true;
    },
};

Page(options);
